﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace Xodeuz.SP.Common
{
    public class SPFeatureHelper
    {

        #region ACTIVATE FEATURE

        public static void EnsureFeature(SPSite site, Guid featureId)
        {
            if (!IsFeatureActivated(site, featureId))
            {
                site.Features.Add(featureId, true);
            }
        }

        public static void EnsureFeature(SPWeb web, Guid featureId)
        {
            if (!IsFeatureActivated(web, featureId))
            {
                web.Features.Add(featureId, true);
            }
        }

        public static void EnsureFeature(SPWebApplication webApp, Guid featureId)
        {
            if (!IsFeatureActivated(webApp, featureId))
            {
                webApp.Features.Add(featureId, true);
            }
        }

        #endregion

        #region DEACTIVATE FEATURE

        public static void RemoveFeature(SPSite site, Guid featureId)
        {
            if (IsFeatureActivated(site, featureId))
            {
                site.Features.Remove(featureId, true);
            }
        }

        public static void RemoveFeature(SPWeb web, Guid featureId)
        {
            if (IsFeatureActivated(web, featureId))
            {
                web.Features.Remove(featureId, true); 
            }
        }

        public static void RemoveFeature(SPWebApplication webApp, Guid featureId)
        {
            if (IsFeatureActivated(webApp, featureId))
            {
                webApp.Features.Remove(featureId, true);
            }
        }

        #endregion

        #region OTHER

        public static bool IsFeatureActivated(SPWebApplication webApp, Guid featureId)
        {
            return webApp.Features[featureId] != null;
        }

        public static bool IsFeatureActivated(SPWeb web, Guid featureId)
        {
            return web.Features[featureId] != null;
        }

        public static bool IsFeatureActivated(SPSite site, Guid featureId)
        {
            return site.Features[featureId] != null;
        }

        #endregion

    }
}
